package com.yang.sms.ali;

import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.yang.businesstool.sms.core.ChannelConstants;
import org.yang.businesstool.sms.core.SendPostProcessor;
import org.yang.businesstool.sms.core.SendResponse;
import org.yang.businesstool.sms.core.SmsSender;

import java.util.LinkedHashMap;

/**
 * @author Billyang
 * @date 2024/9/29 10:16
 */
public class AliSmsSender implements SmsSender {

    private SmsClient client;

    private String signName;

    private SendPostProcessor sendPostProcessor;

    public AliSmsSender(String regionId, String accessKey, String secretKey, String signName) {
        this(regionId, accessKey, secretKey, signName, null);
    }

    public AliSmsSender(String regionId, String accessKey, String secretKey, String signName, SendPostProcessor sendPostProcessor) {
        this.client = new SmsClient(regionId, accessKey, secretKey);
        this.signName = signName;
        this.sendPostProcessor = sendPostProcessor;
    }

    @Override
    public SendResponse send(String mobile, String signName, String templateCode, LinkedHashMap<String, String> templateParamMap, String content) {
        if (StringUtils.isBlank(signName)) {
            signName = this.signName;
        }
        // AliSms的依赖包中含有gson，所以利用gson来处理
        String templateParamJson = new Gson().toJson(templateParamMap);
        SendResponse response = client.send(mobile, signName, templateCode, templateParamJson);
        if (sendPostProcessor != null) {
            sendPostProcessor.afterSend(channel(), mobile, signName, templateCode, templateParamMap, content, response);
        }
        return response;
    }

    @Override
    public String channel() {
        return ChannelConstants.ALI;
    }
}
